package de.tum.in.eist.im.shared.Security;

import java.security.MessageDigest; 
import java.security.NoSuchAlgorithmException; 
 
public class SHAConverter { 
    
	/**
	 * encrypts a string to a SHA256 string
	 * @param text to be encrypted
	 * @return the encrypted string
	 * @throws NoSuchAlgorithmException algorithm not found
	 */
    public static String toSHA256(String text) throws NoSuchAlgorithmException {
    	// copy the string
    	String password = text;
    	 
    	// get a message digest
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update(password.getBytes());
 
        byte byteData[] = md.digest();
 
        //convert the byte to hex format method 1
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < byteData.length; i++) {
         sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
        }
 
        //convert the byte to hex format method 2
        StringBuffer hexString = new StringBuffer();
    	for (int i=0;i<byteData.length;i++) {
    		String hex=Integer.toHexString(0xff & byteData[i]);
   	     	if(hex.length()==1) hexString.append('0');
   	     	hexString.append(hex);
    	}
    	
    	// return the encrypted string
    	return hexString.toString();
    }
} 